package com.weilele.mvvm.utils.task

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.weilele.mvvm.base.livedata.safeSetValue

/**
 * 全局任务，列表里面会有监听的辅助类
 * 能很好处理内存泄露问题
 */
open class TaskMapLiveData<KEY, VALUE> {
    private val liveDataMap = mutableMapOf<KEY, MutableLiveData<VALUE>>()

    /**
     * 获取或者创建liveData，给外部调用或者监听
     */
    fun getOrCreateLiveData(key: KEY): LiveData<VALUE> {
        return getLiveData(key) ?: MutableLiveData<VALUE>().also {
            liveDataMap[key] = it
        }
    }

    /**
     * 获取iveData，给外部调用或者监听
     */
    fun getLiveData(key: KEY): LiveData<VALUE>? {
        return liveDataMap[key]
    }

    /**
     * 移除liveData
     */
    fun removeLiveData(key: KEY) {
        liveDataMap.remove(key)
    }

    /**
     * 更新数据
     */
    fun updateValue(key: KEY, value: VALUE?) {
        (getOrCreateLiveData(key) as MutableLiveData<VALUE>).safeSetValue(value)
    }
}